﻿// 公务车信息管理
function CarIOControl() {

    var BCarFields = new Array(
        { name: 'Id', type: 'string' },
        { name: 'Type', type: 'string' },
        { name: 'CarNo', type: 'string' },
        { name: 'CarOwner', type: 'string' },
        { name: 'DeptID', type: 'string' },
        { name: 'Deptartment', type: 'string' },
        { name: 'Description', type: 'string' },
        { name: 'AuthorizeUsers' }
    );

    // 定义filters
    var filters = new Ext.ux.grid.GridFilters({
        encode: true,
        filters: [{
            dataIndex: 'Brand', // 品牌
            options: ['丰田', '大众', '本田'],
            //options : DeptStore.collect('Name'),
            type: 'list'
        }]
    });

    //查询语句
    filters.buildQuery = function (filters) {
        var p = {}, i, f, root, dataPrefix, key, tmp, len = filters.length;
        if (!this.encode) {
            for (i = 0; i < len; i++) {
                f = filters[i];
                root = [this.paramPrefix, '[', i, ']'].join('');
                p[root + '[field]'] = f.field;

                dataPrefix = root + '[data]';
                for (key in f.data) {
                    p[[dataPrefix, '[', key, ']'].join('')] = f.data[key];
                }
            }
        } else {
            tmp = [];
            for (i = 0; i < len; i++) {
                f = filters[i];
                tmp.push(Ext.apply({}, {
                    field: f.field
                }, f.data));
            }
            if (tmp.length > 0) {
                p[this.paramPrefix] = Ext.util.JSON.encode(tmp);
            }
        }
        return p;
    };

    // 机构Combo Store
    var DeptStore = new Ext.data.JsonStore({
        url: '/InfraHospUser/GetDeptList',
        root: 'data',
        totalProperty: 'total',
        id: 'Id',
        fields: [{
            name: 'Id',
            type: 'string'
        }, {
            name: 'Name',
            type: 'string'
        }, {
            name: 'Code',
            type: 'string'
        }]
    });

    DeptStore.load({
        callback: function (r) {
            filters.addFilter({
                type: 'list',
                dataIndex: 'CurrentDep',
                options: JsHelper.GetFilterListData(r, 'Code', 'Name')
            });
        }
    });

    //字典Store
    var DictStore = function (dictCategory) {
        var dictionaryStore = new Ext.data.JsonStore({
            url: '/InfraDictionary/GetPlistByCategoryCode?Code=' + dictCategory,
            root: 'data',
            totalProperty: 'total',
            id: 'Code',
            fields: [{
                name: 'Id',
                type: 'string'
            }, {
                name: 'Name',
                type: 'string'
            }, {
                name: 'Code',
                type: 'string'
            }]
        });
        return dictionaryStore;
    }

    //与筛选有关的字典dictstore
    var DictFilterStore = function (dictCategory, filters, text, value) {
        var dictStore = DictStore(dictCategory);
        dictStore.load({
            callback: function (r) {
                filters.addFilter({
                    type: 'list',
                    dataIndex: dictCategory,
                    options: JsHelper.GetFilterListData(r, value, text)
                });
            }
        });
        return dictStore;
    }

    //总仓Deport Store
    var TDeportStore = DictFilterStore('TDeport', filters, 'Name', 'Name');
    var BCarTypeStore = DictFilterStore('BCT', filters, 'Name', 'Name');

    // 定义表单 商品车信息Reader
    var CarIOControlFormReader = new Ext.data.JsonReader({
        root: 'data',
        fields: BCarFields
    });

    // 定义表格 商品车信息store
    var itemGridStore = new Ext.data.Store({
        url: "/BCar/GetPlistAll",
        remoteSort: true,
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'total',
            id: 'Id',
            fields: BCarFields
        }),
        listeners: {
            'remove': function (thiz, record, index) {
                Ext.Ajax.request({
                    url: '/BCar/Delete?Id=' + record.data.Id,
                    success: function (response, opts) {
                        var result = Ext.util.JSON.decode(response.responseText);
                        if (result.success == false) {
                            JsHelper.ShowError(result.msg);
                            itemGridStore.insert(0, record);
                        }
                    }
                });
            }
        }
    });
    itemGridStore.setDefaultSort('CreateTime', 'ASC'); // 设置默认排序

    // 定义表格选择方式
    var sm = new Ext.grid.CheckboxSelectionModel();

    // 定义Grid表格列
    var cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), sm, {
        header: "车牌号",
        dataIndex: 'CarNo',
        sortable: true
    }, {
        header: "时间",
        dataIndex: 'LogTime',
        sortable: true
    }, {
        header: "车辆类型",
        dataIndex: 'Type',
        sortable: true
    }, {
        header: "闸机",
        dataIndex: 'Entrance',
        sortable: true
    }, {
        header: "进出",
        dataIndex: 'Entrance',
        sortable: true
    }, {
        header: "值班",
        dataIndex: 'Operator',
        sortable: true
    }, {
        header: "描述",
        dataIndex: 'Description'
    }]);

    //编辑窗口 todo.
    //var showEditFormWinFn2 = Fs.Car.CarForm(formReader, title, itemGridStore, id );


    // 定义表格工具栏
    var tbar = ['快速查找:', '-',
            {
                xtype: 'textfield',
                width: 150,
                id: 'q_query'
            }, "-", {
                xtype: "tbbutton",
                minWidth: 80,
                text: "查询",
                cls: "x-btn-text-icon",
                icon: "/Content/icons/zoom.png",
                handler: function () {
                    var gridStore = grid.getStore();
                    gridStore.load({
                        params: {
                            start: 0,
                            limit: ALL_PAGESIZE_SETTING
                        }
                    });
                }
            }, {
                xtype: "tbbutton",
                minWidth: 80,
                text: "双击修改项",
                cls: "x-btn-text-icon",
                icon: "/Content/icons/pencil.png",
                disabled: true
            }];

    // 分页工具栏
    var bbar = new Ext.PagingToolbar({
        displayInfo: true,
        emptyMsg: "没有数据显示",
        displayMsg: "{0}到{1}条，共{2}条",
        store: itemGridStore,
        pageSize: ALL_PAGESIZE_SETTING,
        plugins: [filters]
    });

    // 商品车信息维护表格
    var grid = new Ext.grid.GridPanel({
        enableColumnMove: false,
        sm: sm,
        cm: cm,
        plugins: [filters],
        stripeRows: true,
        frame: true,
        border: true,
        layout: "fit",
        store: itemGridStore,
        loadMask: true,
        tbar: tbar,
        bbar: bbar,
        listeners: {
            "rowdblclick": function (g, rowIndex, e) {
                var store = g.getStore()
                var id = store.getAt(rowIndex).get("Id");
                //alert("id is : " + id);
                showBCarEditFormWinFn(CarIOControlFormReader, "修改车辆信息", id);
            }
        }
    });

    // 控制删除按钮
    grid.getSelectionModel().on('selectionchange', function (sm) {
        grid.delBtn.setDisabled(sm.getCount() < 1);
    });
        
    // 实时监控显示区域
    var fieldsetCarVideo = new Ext.form.FieldSet({
        title: '出入口监控',
        layout: 'column',
        height: 300,
        items: [{
            xtype: 'box', //或者xtype: 'component',
            id: 'inpic',
            width: 500, //图片宽度
            height: 450, //图片高度
            autoEl: {
                tag: 'img',    //指定为img标签
                //src: '../Piclogs/sample.png'    //指定url路径
                src: '../Content/icons/nopic.gif'    //指定url路径
            }
        }]
    });

    //定义表单列
    var histPicFieldSet = new Ext.form.FieldSet({
        title: '截图',
        //layout: 'border',
        items: [{
            xtype: 'box', //或者xtype: 'component',
            id: 'inpic',
            width: 150, //图片宽度
            height: 150, //图片高度
            autoEl: {
                tag: 'img',    //指定为img标签
                src: '../Content/icons/camera.gif'    //指定url路径
            }
        }]
    });

    var infoColumn = [histPicFieldSet, {
        fieldLabel: 'ID卡',
        xtype: 'textfield',
        width: 150,
        name: 'IDCard',
        emptyText: '双击刷卡...',
        allowBlank: false
    }, {
        fieldLabel: '车牌',
        xtype: 'textfield',
        width: 150,
        name: 'CarNo',
        allowBlank: false
    }, {
        fieldLabel: '类型',
        xtype: 'diccombo',
        store: BCarTypeStore,
        width: 150,
        name: 'Type'
    }, {
        fieldLabel: '值班',
        xtype: 'textfield',
        width: 150,
        name: 'Operator'
    }, {
        xtype: 'textarea',
        fieldLabel: '描述',
        name: 'Description',
        height: 50,
        width: 150
    }];


    // 定义表单 头部固定为两列 末尾单独列 需要改变布局时再修改
    var form = new Ext.FormPanel({
        border: false,
        waitMsgTarget: true,
        labelWidth: 40, // 注意 使用时 如果有表单内组件有特殊标签名称长度很大 替换合适的标签长度
        frame: true,
        bodyStyle: 'padding:5px 5px 0',
        // reader: CarIOControlFormReader, // 注意 这是传入方法的 Ext.data.DataReader 类型
        // 这里的借用表格store的reader属性
        labelAlign: 'right',
        items: infoColumn,
        buttonAlign: 'center',
        buttons: [new Ext.ux.SubmitBtn({
            text : '放行',
            handler: function () {
                if (form.getForm().isValid()) {
                    form.getForm().submit({
                        url: '/BCar/SaveOrUpdate',
                        params: {
                            'AuthorizeUsers': UserCombo.getValue(),
                            'Id': (updateEdit) ? id : ""
                        },
                        success: function (form, action) {
                            itemGridStore.setDefaultSort('CreateTime', 'DESC');
                            itemGridStore.load({// 刷新表格
                                params: {
                                    start: 0,
                                    limit: ALL_PAGESIZE_SETTING
                                }
                            });
                            //win.destroy(); // 关闭窗口
                        },
                        failure: function (form, action) {
                            JsHelper.ShowError(action.result.msg);
                        }
                    }); // formSubmitArgs
                    // 引用之前定义的请求参数变量
                }
            }
        }), new Ext.ux.ResetBtn({
            handler: function () {
                //win.destroy();
            }
        })]
    });

    fieldsetCarVideo.region = 'west';
    fieldsetCarVideo.width = 550;
    form.region = 'center';
    
    var nPanel = new Ext.Panel({
        border: true,
        layout: 'border',
        height: 400,
        items: [fieldsetCarVideo, form]
    });

    nPanel.region = 'north';
    //nPanel.height = '400';
    grid.region = 'center';

    var main = new Ext.Panel({
        border: true,
        layout: 'border',
        items: [nPanel, grid]
    });

    // 加载
    JsHelper.ExtTabDoLayout(main);
    
    itemGridStore.load({
        params: {
            start: 0,
            limit: ALL_PAGESIZE_SETTING
        }
    });
};


CarIOControl();

